/*
 * Copyright (c)  2020,  DataPipeline
 * All rights reserved.
 *
 * Id:LoginController.java   2020-08-18 16:40 wanglijun
 */
package cn.datacare.marmot.web.controller;

import cn.datacare.marmot.bo.MessageVo;
import cn.datacare.marmot.web.Session;
import cn.datacare.marmot.web.controller.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.WebSocketHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2020
 * </p>
 * <p>
 * Company/Department: DataPipeline
 * </p>
 *
 * @author wanglijun
 * @version 1.0
 * @since 2020-08-18 16:40
 */
@Slf4j
@RestController
@RequestMapping("/")
public class LoginController {

    @Autowired
    WebSocketHandler webSocketHandler;

    @Autowired
    SimpMessagingTemplate messagingTemplate;

    /***
     * 登录
     * @param loginVo  登录
     * @param request 密码
     * @return String
     */
    @PostMapping("/login")
    public String login(@RequestBody LoginVo loginVo, HttpServletRequest request,HttpSession httpSession) {
        log.info("loginVo:{}", loginVo.toString());
        log.info("username:{} 登录", loginVo.getUsername());
        httpSession.setAttribute(Session.SESSION_USERNAME, loginVo.getUsername());
        httpSession.setAttribute(Session.SESSION_USER, loginVo);
        return "OK";
    }

    /***
     * 用户名
     * @param httpSession
     * @return
     */
    @GetMapping("/session")
    public String session(HttpSession httpSession) {
        String username = (String) httpSession.getAttribute(Session.SESSION_USERNAME);
        log.info("username:{}",username);
        return username;
    }

    /***
     * 发送消息测试
     * @param loginVo
     * @return String
     */
    @PostMapping("/send")
    public String send(@RequestBody LoginVo loginVo) {
        //this.webSocketHandler.
        return "OK";
    }

    //@Scheduled(fixedRate =10000)
    @GetMapping("/send/topic")
    public void sendTopicMessage() {
        log.info("广播推送消息");
        MessageVo messageVo = new MessageVo();
        messageVo.setAge(17);
        messageVo.setRealName("Evan");
        messageVo.setUsername("scwanglijun");
        this.messagingTemplate.convertAndSend("/topic/message", messageVo);
    }
}
